using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Authorization;
using Microsoft.Extensions.Logging;
using JGSY.CMS.LowCode.Platform.Application.Interfaces;
using JGSY.CMS.LowCode.Platform.Application.DTOs;
using JGSY.CMS.LowCode.Platform.Domain.Enums;

namespace JGSY.CMS.LowCode.Platform.Controllers
{
    /// <summary>
    /// 工作流管理控制器
    /// 提供工作流的增删改查、流程执行、任务管理等功能的 RESTful API
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    [Authorize]
    [Produces("application/json")]
    public class WorkflowsController : ControllerBase
    {
        private readonly IWorkflowAppService _workflowAppService;
        private readonly ILogger<WorkflowsController> _logger;

        public WorkflowsController(
            IWorkflowAppService workflowAppService,
            ILogger<WorkflowsController> logger)
        {
            _workflowAppService = workflowAppService;
            _logger = logger;
        }

        /// <summary>
        /// 获取工作流列表
        /// </summary>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <param name="name">工作流名称</param>
        /// <param name="isEnabled">是否启用</param>
        /// <returns>工作流列表</returns>
        [HttpGet]
        public async Task<IActionResult> GetWorkflows(
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20,
            [FromQuery] string? name = null,
            [FromQuery] bool? isEnabled = null)
        {
            try
            {
                var result = await _workflowAppService.GetPagedAsync(pageIndex, pageSize, name, isEnabled?.ToString());
                return Ok(new
                {
                    Success = true,
                    Message = "获取工作流列表成功",
                    Data = result.Items,
                    Total = result.TotalCount,
                    PageIndex = pageIndex,
                    PageSize = pageSize
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流列表失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取工作流列表失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 根据ID获取工作流
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <returns>工作流详情</returns>
        [HttpGet("{id}")]
        public async Task<IActionResult> GetWorkflow(long id)
        {
            try
            {
                var workflow = await _workflowAppService.GetByIdAsync(id);
                if (workflow == null)
                {
                    return NotFound(new
                    {
                        Success = false,
                        Message = "工作流不存在"
                    });
                }

                return Ok(new
                {
                    Success = true,
                    Message = "获取工作流成功",
                    Data = workflow
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 创建工作流
        /// </summary>
        /// <param name="dto">工作流数据</param>
        /// <returns>创建结果</returns>
        [HttpPost]
        public async Task<IActionResult> CreateWorkflow([FromBody] WorkflowDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new
                    {
                        Success = false,
                        Message = "请求参数无效",
                        Errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)
                    });
                }

                var result = await _workflowAppService.CreateAsync(dto);
                return CreatedAtAction(nameof(GetWorkflow), new { id = result.Id }, new
                {
                    Success = true,
                    Message = "工作流创建成功",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建工作流失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "创建工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 更新工作流
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <param name="dto">工作流数据</param>
        /// <returns>更新结果</returns>
        [HttpPut("{id}")]
        public async Task<IActionResult> UpdateWorkflow(long id, [FromBody] WorkflowDto dto)
        {
            try
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(new
                    {
                        Success = false,
                        Message = "请求参数无效",
                        Errors = ModelState.Values.SelectMany(v => v.Errors).Select(e => e.ErrorMessage)
                    });
                }

                dto.Id = id;
                var result = await _workflowAppService.UpdateAsync(dto);
                if (result == null)
                {
                    return NotFound(new
                    {
                        Success = false,
                        Message = "工作流不存在"
                    });
                }

                return Ok(new
                {
                    Success = true,
                    Message = "工作流更新成功",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "更新工作流失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "更新工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 删除工作流
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <returns>删除结果</returns>
        [HttpDelete("{id}")]
        public async Task<IActionResult> DeleteWorkflow(long id)
        {
            try
            {
                var success = await _workflowAppService.DeleteAsync(id);
                if (!success)
                {
                    return NotFound(new
                    {
                        Success = false,
                        Message = "工作流不存在或删除失败"
                    });
                }

                return Ok(new
                {
                    Success = true,
                    Message = "工作流删除成功"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除工作流失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "删除工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 启动工作流
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <param name="request">启动请求</param>
        /// <returns>启动结果</returns>
        [HttpPost("{id}/start")]
        public async Task<IActionResult> StartWorkflow(
            long id,
            [FromBody] StartWorkflowRequest request)
        {
            try
            {
                var instanceId = await _workflowAppService.StartWorkflowAsync(
                    id, 
                    request.InputData,
                    request.UserId);

                return Ok(new
                {
                    Success = true,
                    Message = "工作流启动成功",
                    Data = new { InstanceId = instanceId }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "启动工作流失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "启动工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 停止工作流
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <param name="request">停止请求</param>
        /// <returns>停止结果</returns>
        [HttpPost("{id}/stop")]
        public async Task<IActionResult> StopWorkflow(
            long id,
            [FromBody] StopWorkflowRequest request)
        {
            try
            {
                var success = await _workflowAppService.StopWorkflowAsync(id, request.Reason);
                return Ok(new
                {
                    Success = success,
                    Message = success ? "工作流停止成功" : "工作流停止失败"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "停止工作流失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "停止工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 将任务置为进行中
        /// </summary>
        [HttpPost("tasks/{taskId:long}/start")]
        public async Task<IActionResult> StartTask(long taskId, [FromBody] TaskActionRequest request)
        {
            try
            {
                var ok = await _workflowAppService.StartTaskAsync(taskId, request.UserId, request.Comment);
                return Ok(new { Success = ok });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "开始任务失败，TaskId: {TaskId}", taskId);
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 完成任务并推进
        /// </summary>
        [HttpPost("tasks/{taskId:long}/complete")]
        public async Task<IActionResult> CompleteTask(long taskId, [FromBody] CompleteTaskRequest request)
        {
            try
            {
                var ok = await _workflowAppService.CompleteTaskAsync(taskId, request.UserId, request.Comment, request.OutputData);
                return Ok(new { Success = ok });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "完成任务失败，TaskId: {TaskId}", taskId);
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 拒绝任务
        /// </summary>
        [HttpPost("tasks/{taskId:long}/reject")]
        public async Task<IActionResult> RejectTask(long taskId, [FromBody] TaskActionRequest request)
        {
            try
            {
                var ok = await _workflowAppService.RejectTaskAsync(taskId, request.UserId, request.Comment);
                return Ok(new { Success = ok });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "拒绝任务失败，TaskId: {TaskId}", taskId);
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 推进实例（自动节点使用）
        /// </summary>
        [HttpPost("instances/{instanceId:long}/advance")]
        public async Task<IActionResult> AdvanceInstance(long instanceId)
        {
            try
            {
                var ok = await _workflowAppService.AdvanceInstanceAsync(instanceId);
                return Ok(new { Success = ok });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "推进实例失败，InstanceId: {InstanceId}", instanceId);
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 暂停工作流
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <returns>暂停结果</returns>
        [HttpPost("{id}/pause")]
        public async Task<IActionResult> PauseWorkflow(long id)
        {
            try
            {
                var success = await _workflowAppService.PauseWorkflowAsync(id);
                return Ok(new
                {
                    Success = success,
                    Message = success ? "工作流暂停成功" : "工作流暂停失败"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "暂停工作流失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "暂停工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 恢复工作流
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <returns>恢复结果</returns>
        [HttpPost("{id}/resume")]
        public async Task<IActionResult> ResumeWorkflow(long id)
        {
            try
            {
                var success = await _workflowAppService.ResumeWorkflowAsync(id);
                return Ok(new
                {
                    Success = success,
                    Message = success ? "工作流恢复成功" : "工作流恢复失败"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "恢复工作流失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "恢复工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取工作流实例列表
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <param name="status">状态筛选</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <returns>实例列表</returns>
        [HttpGet("{id}/instances")]
        public async Task<IActionResult> GetWorkflowInstances(
            long id,
            [FromQuery] string? status = null,
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                var result = await _workflowAppService.GetWorkflowInstancesAsync(
                    id, status, pageIndex, pageSize);

                return Ok(new
                {
                    Success = true,
                    Message = "获取工作流实例成功",
                    Data = result.Items,
                    Total = result.TotalCount,
                    PageIndex = pageIndex,
                    PageSize = pageSize
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流实例失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取工作流实例失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取工作流统计信息
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <returns>统计信息</returns>
        [HttpGet("{id}/statistics")]
        public async Task<IActionResult> GetWorkflowStatistics(long id)
        {
            try
            {
                var statistics = await _workflowAppService.GetWorkflowStatisticsAsync(id);
                return Ok(new
                {
                    Success = true,
                    Message = "获取工作流统计信息成功",
                    Data = statistics
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流统计信息失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取工作流统计信息失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取工作流执行历史
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <param name="pageIndex">页索引</param>
        /// <param name="pageSize">页大小</param>
        /// <returns>执行历史</returns>
        [HttpGet("{id}/history")]
        public async Task<IActionResult> GetExecutionHistory(
            long id,
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                var result = await _workflowAppService.GetExecutionHistoryAsync(
                    id, pageIndex, pageSize);

                return Ok(new
                {
                    Success = true,
                    Message = "获取执行历史成功",
                    Data = result.Items,
                    Total = result.TotalCount,
                    PageIndex = pageIndex,
                    PageSize = pageSize
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取执行历史失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取执行历史失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取全局统计信息
        /// </summary>
        /// <returns>全局统计信息</returns>
        [HttpGet("statistics")]
        public async Task<IActionResult> GetGlobalStatistics()
        {
            try
            {
                var statistics = await _workflowAppService.GetGlobalStatisticsAsync();
                return Ok(new
                {
                    Success = true,
                    Message = "获取全局统计信息成功",
                    Data = statistics
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取全局统计信息失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取全局统计信息失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 导出工作流
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <param name="format">导出格式 (json/xml/yaml)</param>
        /// <returns>导出文件</returns>
        [HttpGet("{id}/export")]
        public async Task<IActionResult> ExportWorkflow(long id, [FromQuery] string format = "json")
        {
            try
            {
                var exportData = await _workflowAppService.ExportWorkflowAsync(id, format);
                if (string.IsNullOrEmpty(exportData))
                {
                    return NotFound(new
                    {
                        Success = false,
                        Message = "工作流不存在"
                    });
                }

                var contentType = format.ToLower() switch
                {
                    "xml" => "application/xml",
                    "yaml" => "application/x-yaml",
                    _ => "application/json"
                };

                var fileExtension = format.ToLower() switch
                {
                    "xml" => "xml",
                    "yaml" => "yaml",
                    _ => "json"
                };

                var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
                return File(bytes, contentType, $"workflow_{id}_{DateTime.Now:yyyyMMddHHmmss}.{fileExtension}");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导出工作流失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "导出工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 批量导出工作流
        /// </summary>
        /// <param name="ids">工作流ID列表</param>
        /// <param name="format">导出格式 (json/xml/yaml)</param>
        /// <returns>导出的ZIP文件</returns>
        [HttpPost("export/batch")]
        public async Task<IActionResult> ExportWorkflows([FromBody] long[] ids, [FromQuery] string format = "json")
        {
            try
            {
                if (ids == null || ids.Length == 0)
                {
                    return BadRequest(new
                    {
                        Success = false,
                        Message = "请选择要导出的工作流"
                    });
                }

                var zipData = await _workflowAppService.ExportWorkflowsAsZipAsync(ids, format);
                return File(zipData, "application/zip", $"workflows_export_{DateTime.Now:yyyyMMddHHmmss}.zip");
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量导出工作流失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "批量导出工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 导入工作流
        /// </summary>
        /// <param name="file">导入文件</param>
        /// <param name="overwrite">是否覆盖同名工作流</param>
        /// <returns>导入结果</returns>
        [HttpPost("import")]
        public async Task<IActionResult> ImportWorkflow(IFormFile file, [FromQuery] bool overwrite = false)
        {
            try
            {
                if (file == null || file.Length == 0)
                {
                    return BadRequest(new
                    {
                        Success = false,
                        Message = "请选择文件"
                    });
                }

                // 支持JSON和ZIP文件
                var allowedTypes = new[] { "application/json", "text/json", "application/zip", "application/x-zip-compressed" };
                if (!allowedTypes.Any(type => file.ContentType.Contains(type, StringComparison.OrdinalIgnoreCase)))
                {
                    return BadRequest(new
                    {
                        Success = false,
                        Message = "文件格式不正确，请选择JSON或ZIP文件"
                    });
                }

                using var stream = new MemoryStream();
                await file.CopyToAsync(stream);

                if (file.ContentType.Contains("zip"))
                {
                    // 处理ZIP文件（批量导入）
                    var results = await _workflowAppService.ImportWorkflowsFromZipAsync(stream.ToArray(), overwrite);
                    return Ok(new
                    {
                        Success = true,
                        Message = $"批量导入完成，成功导入 {results.SuccessCount} 个工作流，失败 {results.FailCount} 个",
                        Data = new
                        {
                            SuccessCount = results.SuccessCount,
                            FailCount = results.FailCount,
                            SuccessWorkflows = results.SuccessWorkflows,
                            FailedImports = results.FailedImports
                        }
                    });
                }
                else
                {
                    // 处理单个JSON文件
                    var jsonData = System.Text.Encoding.UTF8.GetString(stream.ToArray());
                    var workflow = await _workflowAppService.ImportWorkflowAsync(jsonData, overwrite);
                    return Ok(new
                    {
                        Success = true,
                        Message = "工作流导入成功",
                        Data = workflow
                    });
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "导入工作流失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "导入工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 复制工作流
        /// </summary>
        /// <param name="id">工作流ID</param>
        /// <param name="request">复制请求</param>
        /// <returns>复制结果</returns>
        [HttpPost("{id}/copy")]
        public async Task<IActionResult> CopyWorkflow(long id, [FromBody] CopyWorkflowRequest request)
        {
            try
            {
                var newWorkflow = await _workflowAppService.CopyWorkflowAsync(id, request.NewName);
                if (newWorkflow == null)
                {
                    return NotFound(new
                    {
                        Success = false,
                        Message = "源工作流不存在"
                    });
                }

                return Ok(new
                {
                    Success = true,
                    Message = "工作流复制成功",
                    Data = newWorkflow
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "复制工作流失败，ID: {Id}", id);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "复制工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 获取运行中的工作流
        /// </summary>
        /// <returns>运行中的工作流列表</returns>
        [HttpGet("running")]
        public async Task<IActionResult> GetRunningWorkflows()
        {
            try
            {
                var workflows = await _workflowAppService.GetRunningWorkflowsAsync();
                return Ok(new
                {
                    Success = true,
                    Message = "获取运行中的工作流成功",
                    Data = workflows
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取运行中的工作流失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取运行中的工作流失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 清理过期实例
        /// </summary>
        /// <param name="request">清理请求</param>
        /// <returns>清理结果</returns>
        [HttpPost("cleanup")]
        public async Task<IActionResult> CleanupExpiredInstances([FromBody] CleanupRequest request)
        {
            try
            {
                var deletedCount = await _workflowAppService.CleanupExpiredInstancesAsync(request.DaysToKeep);
                return Ok(new
                {
                    Success = true,
                    Message = $"清理完成，删除了 {deletedCount} 个过期实例",
                    Data = new { DeletedCount = deletedCount }
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "清理过期实例失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "清理过期实例失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 我的待办任务
        /// </summary>
        [HttpGet("my/tasks")]
        public async Task<IActionResult> GetMyPendingTasks(
            [FromQuery] long userId,
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20,
            [FromQuery] int? priority = null,
            [FromQuery] DateTime? dueBefore = null,
            [FromQuery] string? keyword = null)
        {
            try
            {
                var result = await _workflowAppService.GetMyPendingTasksAsync(userId, pageIndex, pageSize, priority, dueBefore, keyword);
                return Ok(new { Success = true, Data = result.Items, Total = result.TotalCount, PageIndex = pageIndex, PageSize = pageSize });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取我的待办任务失败");
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 我发起的实例
        /// </summary>
        [HttpGet("my/instances")]
        public async Task<IActionResult> GetMyInitiatedInstances(
            [FromQuery] long userId,
            [FromQuery] int? status = null,
            [FromQuery] int pageIndex = 1,
            [FromQuery] int pageSize = 20)
        {
            try
            {
                WorkflowInstanceStatus? s = null;
                if (status.HasValue)
                {
                    s = (WorkflowInstanceStatus)status.Value;
                }
                var result = await _workflowAppService.GetMyInitiatedInstancesAsync(userId, s, pageIndex, pageSize);
                return Ok(new { Success = true, Data = result.Items, Total = result.TotalCount, PageIndex = pageIndex, PageSize = pageSize });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取我发起的实例失败");
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 刷新超时任务状态
        /// </summary>
        [HttpPost("tasks/refresh-overdue")]
        public async Task<IActionResult> RefreshOverdueTasks()
        {
            try
            {
                var count = await _workflowAppService.RefreshOverdueTasksAsync();
                return Ok(new { Success = true, Message = $"已标记 {count} 个超时任务" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "刷新超时任务失败");
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 获取工作流实例详情
        /// </summary>
        /// <param name="instanceId">实例ID</param>
        /// <returns>实例详情</returns>
        [HttpGet("instances/{instanceId:long}")]
        public async Task<IActionResult> GetWorkflowInstance(long instanceId)
        {
            try
            {
                var instance = await _workflowAppService.GetWorkflowInstanceDetailAsync(instanceId);
                if (instance == null)
                {
                    return NotFound(new
                    {
                        Success = false,
                        Message = "工作流实例不存在"
                    });
                }

                return Ok(new
                {
                    Success = true,
                    Message = "获取工作流实例详情成功",
                    Data = instance
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流实例详情失败，InstanceId: {InstanceId}", instanceId);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "获取工作流实例详情失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 停止工作流实例
        /// </summary>
        /// <param name="instanceId">实例ID</param>
        /// <param name="reason">停止原因</param>
        /// <returns>停止结果</returns>
        [HttpPost("instances/{instanceId:long}/stop")]
        public async Task<IActionResult> StopWorkflowInstance(long instanceId, [FromBody] string? reason = null)
        {
            try
            {
                var success = await _workflowAppService.StopWorkflowInstanceAsync(instanceId, reason);
                return Ok(new
                {
                    Success = success,
                    Message = success ? "工作流实例停止成功" : "工作流实例停止失败"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "停止工作流实例失败，InstanceId: {InstanceId}", instanceId);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "停止工作流实例失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 重试工作流实例
        /// </summary>
        /// <param name="instanceId">实例ID</param>
        /// <returns>重试结果</returns>
        [HttpPost("instances/{instanceId:long}/retry")]
        public async Task<IActionResult> RetryWorkflowInstance(long instanceId)
        {
            try
            {
                var success = await _workflowAppService.RetryWorkflowInstanceAsync(instanceId);
                return Ok(new
                {
                    Success = success,
                    Message = success ? "工作流实例重试成功" : "工作流实例重试失败"
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "重试工作流实例失败，InstanceId: {InstanceId}", instanceId);
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "重试工作流实例失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 批量操作工作流实例
        /// </summary>
        /// <param name="request">批量操作请求</param>
        /// <returns>操作结果</returns>
        [HttpPost("instances/batch")]
        public async Task<IActionResult> BatchOperateInstances([FromBody] BatchInstanceOperationRequest request)
        {
            try
            {
                if (request.InstanceIds == null || !request.InstanceIds.Any())
                {
                    return BadRequest(new
                    {
                        Success = false,
                        Message = "请选择要操作的实例"
                    });
                }

                var result = await _workflowAppService.BatchOperateInstancesAsync(request.InstanceIds, request.Operation, request.Reason);
                return Ok(new
                {
                    Success = true,
                    Message = $"批量操作完成，成功: {result.SuccessCount}，失败: {result.FailCount}",
                    Data = result
                });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "批量操作工作流实例失败");
                return StatusCode(500, new
                {
                    Success = false,
                    Message = "批量操作工作流实例失败",
                    Error = ex.Message
                });
            }
        }

        /// <summary>
        /// 创建工作流版本快照
        /// </summary>
        [HttpPost("{id}/versions")]
        public async Task<IActionResult> CreateWorkflowVersion(long id, [FromBody] CreateWorkflowVersionRequest request)
        {
            try
            {
                var version = await _workflowAppService.CreateVersionAsync(id, request.Tag, request.Description, request.UserId);
                return Ok(new { Success = true, Message = "版本创建成功", Data = version });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "创建工作流版本失败，ID: {Id}", id);
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 获取工作流的所有版本
        /// </summary>
        [HttpGet("{id}/versions")]
        public async Task<IActionResult> GetWorkflowVersions(long id)
        {
            try
            {
                var versions = await _workflowAppService.GetVersionsAsync(id);
                return Ok(new { Success = true, Data = versions });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流版本列表失败，ID: {Id}", id);
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 获取指定版本详情
        /// </summary>
        [HttpGet("{id}/versions/{version:int}")]
        public async Task<IActionResult> GetWorkflowVersion(long id, int version)
        {
            try
            {
                var v = await _workflowAppService.GetVersionAsync(id, version);
                if (v == null)
                    return NotFound(new { Success = false, Message = "指定版本不存在" });
                return Ok(new { Success = true, Data = v });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取工作流版本失败，ID: {Id}, Version: {Version}", id, version);
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }

        /// <summary>
        /// 回滚到指定版本
        /// </summary>
        [HttpPost("{id}/versions/{version:int}/rollback")]
        public async Task<IActionResult> RollbackWorkflowVersion(long id, int version, [FromBody] RollbackWorkflowVersionRequest request)
        {
            try
            {
                var ok = await _workflowAppService.RollbackToVersionAsync(id, version, request.UserId, request.Reason);
                return Ok(new { Success = ok, Message = ok ? "回滚成功" : "回滚失败" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "回滚工作流版本失败，ID: {Id}, Version: {Version}", id, version);
                return StatusCode(500, new { Success = false, Message = ex.Message });
            }
        }
    }

    /// <summary>
    /// 启动工作流请求
    /// </summary>
    public class StartWorkflowRequest
    {
        /// <summary>
        /// 用户ID
        /// </summary>
        public long? UserId { get; set; }

        /// <summary>
        /// 输入数据
        /// </summary>
        public Dictionary<string, object>? InputData { get; set; }
    }

    /// <summary>
    /// 停止工作流请求
    /// </summary>
    public class StopWorkflowRequest
    {
        /// <summary>
        /// 停止原因
        /// </summary>
        public string? Reason { get; set; }
    }

    /// <summary>
    /// 复制工作流请求
    /// </summary>
    public class CopyWorkflowRequest
    {
        /// <summary>
        /// 新名称
        /// </summary>
        public string NewName { get; set; } = string.Empty;
    }

    /// <summary>
    /// 清理请求
    /// </summary>
    public class CleanupRequest
    {
        /// <summary>
        /// 保留天数
        /// </summary>
        public int DaysToKeep { get; set; } = 30;
    }

    /// <summary>
    /// 通用任务操作请求
    /// </summary>
    public class TaskActionRequest
    {
        public long UserId { get; set; }
        public string? Comment { get; set; }
    }

    /// <summary>
    /// 完成任务请求
    /// </summary>
    public class CompleteTaskRequest : TaskActionRequest
    {
        public Dictionary<string, object>? OutputData { get; set; }
    }

    /// <summary>
    /// 创建版本请求
    /// </summary>
    public class CreateWorkflowVersionRequest
    {
        public string? Tag { get; set; }
        public string? Description { get; set; }
        public long? UserId { get; set; }
    }

    /// <summary>
    /// 回滚版本请求
    /// </summary>
    public class RollbackWorkflowVersionRequest
    {
        public long? UserId { get; set; }
        public string? Reason { get; set; }
    }
}
